// pages/order/order.js
const app = getApp()
import config from '../../utils/config.js';
import util from '../../utils/util.js';
import Toast from '../../vant/toast/toast';
import Dialog from '../../vant/dialog/dialog';
import {
  orderModel
} from '../../models/order';
const order = new orderModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    config: config,
    height: app.globalData.height,
    barheight: app.globalData.barheight,
    realWindowWidth: app.globalData.realWindowHeight,
    realWindowHeight: app.globalData.realWindowHeight,
    sysBottom: app.globalData.bottom,
    activeIdx: 2,
	
	  fLoad:true,  // 是否第一次打开页面

    scroll_height:'',
	  ifRefresh:false,  // 是否刷新数据

    updateOrderStatus: '', // 是否改单 0否1是
    page: 1, // 第几页
    size: 15,
    endFlag: false, // 是否到最后
    dataList: [], // 列表

    // --- 筛选查询 start ---
    show: false,
    show1: false,
    show2: false,
    date: '',//默认起始时间  
    date2: '',//默认结束时间 
    minDate1: 0,
    maxDate: new Date().getTime(),
    maxDate1: new Date().getTime(),
    currentDate: new Date().getTime(), 
    currentDate1: new Date().getTime(), 
    active: '',
    sactive: '',
    active2: '',
    sactive2: '',
    // --- 筛选查询 end ---

    // --- 导出 start ---
    show3: false,
    eactive: '',
    edate: '',//默认起始时间  
    edate2: '',//默认结束时间 
    eminDate1: 0,
    emaxDate: 0,
    emaxDate1: 0,
    ecurrentDate: new Date().getTime(), 
    ecurrentDate1: new Date().getTime(), 
    // --- 导出 end ---

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 隐藏原生的tabbar
    wx.hideTabBar()
    // 设置content高度
    var scroll_height = this.data.realWindowHeight-this.data.barheight-this.data.height-50-(49+this.data.sysBottom);
    var newDate = new Date()
    var year = newDate.getFullYear()+1;
    var emaxDate = new Date(year+'/12/31').getTime()
    this.setData({
      scroll_height: scroll_height,
      emaxDate: emaxDate,
      emaxDate1: emaxDate
    })
    this.data.fLoad = true

    this.getAuth();
  },
  getAuth() {
    var _this = this
    wx.request({
      url: config.projectUrl + 'canteen/canteen/currentCanteenInfo',
      method: 'get',
      header: {
        'authentication': wx.getStorageSync('authentication')
      },
      success: function (res) {
        if(res.data.code == '402'){
          Dialog.confirm({
            title: '提示',
            message: '您还未登录，请先登录再进行操作',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            wx.reLaunch({
              url: '/pages/login/login'
            })
          }).catch(() => {
            // on cancel
          });
        }else{
          _this.getList();
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
	  if(!this.data.fLoad){
      this.setData({
        allPage: 0,
        page: 1,
        endFlag: false,
        dataList: []
      })
      // this.data.allPage = 0, // 所有页数
      // this.data.page = 1, // 第几页
      // this.data.endFlag = false, // 是否到最后
      // this.data.dataList = [], // 列表
      this.getAuth();
	  }
	  this.data.fLoad = false
  },

  // 卡片列表
  getList(){
    order.apiorderCaPage({
      page: this.data.page,
      limit: this.data.size,
      startTime: this.data.startTime,
      endTime: this.data.endTime,
      orderStatus: this.data.orderStatus,
      updateOrderStatus: this.data.updateOrderStatus
    }, res =>{
      if (res.list.length > 0) {
        var page = this.data.page;
        var endFlag = false;
        var allPage = res.allPage;
        if (page == allPage) {
          endFlag = true;
        } else {
          page += 1;
        }
        var dataList = this.data.dataList;
        if (page != 1) {
          dataList = dataList.concat(res.list);
        } else {
          dataList = res.list;
        }
        this.setData({
          dataList: dataList,
          endFlag: endFlag,
          page: page
        });
      }
    })
  },

  // 滑动至底部
  producScroll(){
    if (this.data.endFlag) {
      util.msg('没有更多了~');
      return;
    } else {
      this.getList();
    }
  },

  onTab(e){
    var index = e.currentTarget.dataset.index
    if(this.data.show){ // 筛选查询
      this.setData({
        active: index
      })
    }else if(this.data.show3){ // 导出配货单
      let eactive = this.data.eactive
      if(index){
        index = Number(index)
        if(!eactive){
          eactive = []
        }
        if(eactive.indexOf(index)<0){
          eactive.push(index)
        }else{
          eactive.splice(eactive.indexOf(index),1)
        }
      }
      this.setData({
        eactive: !index?'':eactive
      })
      // console.log(this.data.eactive)
    }
  },
  onSTab(e){
    var index = e.currentTarget.dataset.index
    this.setData({
      sactive: index
    })
  },
  
  // 开始时间  
  onDeliveryTime(e) {
    this.setData({
      show1: true
    })
  },
  onConfirm0(event) {
    var currentDate = event.detail
    if(this.data.show){
      if(event.detail>this.data.currentDate1){
        currentDate = this.data.currentDate1
      }
      var date = util.formatTimeTwo(currentDate,'Y-M-D')
      this.setData({
        currentDate: currentDate,
        date: date,
        show1: false,
      });
    }else if(this.data.show3){ // 导出
      if(event.detail>this.data.ecurrenteDate1){
        currentDate = this.data.ecurrenteDate1
      }
      var date = util.formatTimeTwo(currentDate,'Y-M-D h:m:s')
      this.setData({
        ecurrentDate: currentDate,
        edate: date,
        show1: false,
      });
    }
  },
  onCancel0(){
    this.setData({
      show1: false
    })
  },
  // 结束时间
  onArriveTime(e) {
    this.setData({
      show2: true
    })
  },
  onConfirm1(event) {
    var currentDate1 = event.detail
    if(this.data.show){
      if(event.detail<this.data.currentDate){
        currentDate1 = this.data.currentDate
      }
      var date2 = util.formatTimeTwo(currentDate1,'Y-M-D')
      this.setData({
        currentDate1: currentDate1,
        date2: date2,
        show2: false,
      });
    }else if(this.data.show3){
      if(event.detail<this.data.ecurrentDate){
        currentDate1 = this.data.ecurrentDate
      }
      var date2 = util.formatTimeTwo(currentDate1,'Y-M-D h:m:s')
      this.setData({
        ecurrentDate1: currentDate1,
        edate2: date2,
        show2: false,
      });
    }
  },
  onCancel1(){
    this.setData({
      show2: false
    })
  },
  onReset(){
    if(this.data.show){
      this.setData({
        date: '',
        date2: '',
        minDate1: 0,
        maxDate: new Date().getTime()-86400000,
        maxDate1: new Date().getTime(),
        currentDate: new Date().getTime()-86400000, 
        currentDate1: new Date().getTime()
      })
    }else if(this.data.show3){
      var newDate = new Date()
      var year = newDate.getFullYear()+1;
      var emaxDate = new Date(year+'/12/31').getTime()
      this.setData({
        edate: '',
        edate2: '',
        eminDate1: 0,
        emaxDate: emaxDate,
        emaxDate1: emaxDate,
        ecurrentDate: new Date().getTime()-86400000, 
        ecurrentDate1: new Date().getTime()
      })
    }
  },

  // 筛选
  onFilter(){
    this.setData({
      show: true
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  onSearch(){
    // if(this.data.date&&this.data.date2)
      this.setData({
        startTime: this.data.date,
        endTime: this.data.date2
      })
    this.setData({
      active2:this.data.active,
      sactive2:this.data.sactive,
      orderStatus: this.data.active,
      updateOrderStatus: this.data.sactive==2?0:this.data.sactive,
      show: false,
      allPage: 0, // 所有页数
      page: 1, // 第几页
      endFlag: false, // 是否到最后
      dataList: [], // 订单列表
    })
    this.getList()
  },

  // 订单归类卡片
  onClasslist: util.throttle(function (e) { 
    var time = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/order/orderClass/orderClass?time='+time+'&active='+this.data.active2+'&sactive='+this.data.sactive2,
    })
  }),

  // 导出
  onExport: util.throttle(function (e) { 
    this.setData({
      show3: true
    })
  }),

  // 导出弹出窗关闭
  onClose3() {
    this.setData({
      show3: false
    })
  },

  // 导出确认
  onESure: util.throttle(function(e) {
    var params = '?startTime='+this.data.edate+'&endTime='+this.data.edate2
    if(this.data.eactive){
      params += '&orderStatusSet='+this.data.eactive.toString()
    }
    order.exportOrder(params, res => {
      const filePath = res.tempFilePath
      const fs = wx.getFileSystemManager();
      fs.saveFile({
        tempFilePath:filePath,//Path我这里是wx.downloadFile()下载下来的文件临时地址
        //wx.env.USER_DATA_PATH这个是微信文件的路径  没试过别的  别的路径一般没有权限
        filePath: wx.env.USER_DATA_PATH + '/喜餐' + Date.parse(new Date()) + '.xlsx',
        success:function(res){
          console.log(res)
          wx.openDocument({
            filePath: res.savedFilePath,
            showMenu: true,
            fileType: 'xlsx',
            success: function (res) {
              console.log('打开文档成功')
            }
          })

        },
        fail:function(res){
          console.log(res)
        }
      })
    })
  }),

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      allPage: 0, // 所有页数
      page: 1, // 第几页
      endFlag: false, // 是否到最后
      dataList: [], // 商品列表
    })
    this.onLoad();
    //模拟加载 		
    setTimeout(function () {		
      wx.hideNavigationBarLoading() //完成停止加载 			
      wx.stopPullDownRefresh() //停止下拉刷新 		
    }, 1500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.endFlag) {
      util.msg('没有更多了~');
      return;
    } else {
      this.getList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})